import { Controller } from 'egg';

export default class UserController extends Controller {

  // 展示
  public async index() {
    const { ctx, app } = this
    const { currentPage, pageSize } = ctx.queries
    const token = ctx.request.header.authorization;

    // 解码token 判断是否是管理员，非管理员不发送数据
    const decode: any = await app.jwt.verify(token as any, app.config.jwt.secret);
    const userRes: any = await ctx.service.user.selectByUsername(decode['username'])
    if (userRes[0].role == 'admin') {
      const users = await ctx.service.user.selectAll()
      const total = users.length
      const pageData = users.splice((Number(currentPage) - 1) * Number(pageSize), Number(pageSize))

      ctx.body = {
        code: 2000,
        pageData,
        total
      }
    } else {
      ctx.body = {
        code: 4003,
        msg: '权限不足'
      }
    }
  }

  // 添加
  public async new() {
    const { ctx } = this
    const { user } = ctx.request.body
    await ctx.service.user.addOne(user)
    ctx.body = {
      code: 2000,
      msg: '添加成功',
    }
  }

  // 删除
  public async destroy() {
    const { ctx } = this
    const { id } = ctx.queries
    const res = await ctx.service.user.delById(id)
    let msg = ''
    if (res.affectedRows > 0) {
      msg = '删除成功'
    } else {
      msg = '删除失败'
    }
    ctx.body = {
      code: 2000,
      msg,
    }
  }

  // 修改
  public async update() {
    const { ctx } = this
    const { user } = ctx.request.body
    const res = await ctx.service.user.updateById(user)
    let msg = '修改失败'
    if (res.affectedRows > 0) {
      msg = '修改成功'
    }
    ctx.body = {
      code: 2000,
      msg
    }
  }
}